@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>节假日设置管理</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        .search-container {
            background: #fff;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .table-container {
            background: #fff;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .search-form .layui-form-item {
            margin-bottom: 15px;
        }
        .toolbar {
            padding: 15px;
            border-bottom: 1px solid #e6e6e6;
        }
        .holiday-type-tag {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            color: white;
            display: inline-block;
        }
        .type-holiday { background: #ff4d4f; }
        .type-workday { background: #52c41a; }
        .type-weekend { background: #1890ff; }
        .layui-table-cell {
            height: auto;
            line-height: 28px;
        }
        .calendar-view {
            background: #fff;
            padding: 20px;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .calendar-header {
            margin-bottom: 20px;
            text-align: center;
        }
        .calendar-nav {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
        }
        .calendar-nav span {
            font-size: 20px;
            font-weight: 500;
            color: #333;
            min-width: 150px;
        }
        .calendar-table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
        }
        .calendar-table th {
            background: #f8f9fa;
            padding: 15px 5px;
            text-align: center;
            border: 1px solid #e6e6e6;
            font-weight: 500;
            color: #666;
        }
        .calendar-table td {
            height: 100px;
            border: 1px solid #e6e6e6;
            vertical-align: top;
            padding: 5px;
            position: relative;
        }
        .calendar-date {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 5px;
        }
        .calendar-lunar {
            font-size: 12px;
            color: #999;
            margin-bottom: 5px;
        }
        .calendar-holiday {
            font-size: 11px;
            background: #52c41a;
            color: white;
            padding: 1px 4px;
            border-radius: 2px;
            display: inline-block;
            margin-bottom: 2px;
        }
        .calendar-workday {
            background: #1890ff;
        }
        .calendar-special {
            background: #ff4d4f;
        }
        .calendar-day {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .calendar-day:hover {
            background: #f0f8ff;
        }
        .calendar-day.today {
            background: #e6f7ff;
            border: 2px solid #1890ff;
        }
        .calendar-day.other-month {
            color: #ccc;
        }
        .calendar-day.weekend {
            background: #fafafa;
        }
        .calendar-day.holiday {
            background: #fff2f0;
        }
    </style>
</head>
<body>
    <div class="layui-container-fluid">
        <!-- 搜索条件区域 -->
        <div class="search-container" style="display: none;">
            <form class="layui-form search-form" lay-filter="searchForm">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">年份</label>
                            <div class="layui-input-block">
                                <select name="year">
                                    <option value="">请选择年份</option>
                                    <option value="2024">2024年</option>
                                    <option value="2025" selected>2025年</option>
                                    <option value="2026">2026年</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">月份</label>
                            <div class="layui-input-block">
                                <select name="month">
                                    <option value="">请选择月份</option>
                                    <option value="1">1月</option>
                                    <option value="2">2月</option>
                                    <option value="3">3月</option>
                                    <option value="4">4月</option>
                                    <option value="5">5月</option>
                                    <option value="6" selected>6月</option>
                                    <option value="7">7月</option>
                                    <option value="8">8月</option>
                                    <option value="9">9月</option>
                                    <option value="10">10月</option>
                                    <option value="11">11月</option>
                                    <option value="12">12月</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">节假日类型</label>
                            <div class="layui-input-block">
                                <select name="holidayType">
                                    <option value="">请选择类型</option>
                                    <option value="holiday">法定节假日</option>
                                    <option value="workday">调休工作日</option>
                                    <option value="weekend">周末</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">节假日名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="holidayName" placeholder="请输入节假日名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">日期范围</label>
                            <div class="layui-input-block">
                                <input type="text" name="dateRange" placeholder="开始日期 - 结束日期" class="layui-input" id="dateRange">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md9">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="text-align: right; margin-left: 0;">
                                <button type="button" class="layui-btn" lay-submit lay-filter="searchBtn">
                                    <i class="layui-icon layui-icon-search"></i> 搜索
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="calendarViewBtn">
                                    <i class="layui-icon layui-icon-date"></i> 日历视图
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-container" style="display: none;">
            <!-- 工具栏 -->
            <div class="toolbar">
                <div class="layui-btn-group">
                    <button class="layui-btn layui-btn-sm" id="addBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 新增节假日
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-normal" id="editBtn">
                        <i class="layui-icon layui-icon-edit"></i> 修改
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-danger" id="deleteBtn">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-warm" id="importBtn">
                        <i class="layui-icon layui-icon-upload"></i> 批量导入
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-warm" id="exportBtn">
                        <i class="layui-icon layui-icon-export"></i> 导出
                    </button>
                </div>
            </div>
            
            <!-- 数据表格 -->
            <table class="layui-hide" id="holidaysTable" lay-filter="holidaysTable"></table>
        </div>

        <!-- 日历视图区域 -->
        <div class="calendar-view" id="calendarView">
            <div class="calendar-header">
                <div class="calendar-nav">
                    <button class="layui-btn layui-btn-sm layui-btn-primary" id="prevMonth">
                        <i class="layui-icon layui-icon-left"></i> 上个月
                    </button>
                    <span id="calendarTitle">2025年8月</span>
                    <button class="layui-btn layui-btn-sm layui-btn-primary" id="nextMonth">
                        今天 <i class="layui-icon layui-icon-right"></i>
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-primary" id="nextMonth2">
                        下个月 <i class="layui-icon layui-icon-right"></i>
                    </button>
                </div>
            </div>
            <div class="calendar-content">
                <table class="calendar-table">
                    <thead>
                        <tr>
                            <th>一</th>
                            <th>二</th>
                            <th>三</th>
                            <th>四</th>
                            <th>五</th>
                            <th>六</th>
                            <th>日</th>
                        </tr>
                    </thead>
                    <tbody id="calendarBody">
                        <!-- 日历内容将通过JavaScript生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        layui.use(['layer'], function() {
            var layer = layui.layer;

            // 确保DOM已完全加载
            $(document).ready(function() {
                initializeCalendar();
            });

            function initializeCalendar() {
                console.log('开始初始化日历...');
                
                // 当前显示的年月
                var today = new Date();
                var currentYear = today.getFullYear();
                var currentMonth = today.getMonth() + 1;

                // 节假日数据（由服务器动态加载）
                var holidayData = {};

            // 获取农历信息（简化版）
            function getLunarInfo(date) {
                // 这里可以集成农历转换库，暂时返回空
                return '';
            }

            // 生成日历
            function generateCalendar(year, month) {
                console.log('生成日历:', year + '年' + month + '月');
                var calendarBody = $('#calendarBody');
                if (calendarBody.length === 0) {
                    console.error('找不到日历表格体元素');
                    return;
                }
                calendarBody.empty();
                
                // 更新标题
                $('#calendarTitle').text(year + '年' + month + '月');
                
                // 获取当月第一天和最后一天
                var firstDay = new Date(year, month - 1, 1);
                var lastDay = new Date(year, month, 0);
                var firstDayWeek = firstDay.getDay(); // 0=周日, 1=周一...
                var daysInMonth = lastDay.getDate();
                
                // 调整为周一开始
                firstDayWeek = firstDayWeek === 0 ? 6 : firstDayWeek - 1;
                
                // 获取上个月的天数
                var prevMonth = month === 1 ? 12 : month - 1;
                var prevYear = month === 1 ? year - 1 : year;
                var prevMonthDays = new Date(prevYear, prevMonth, 0).getDate();
                
                var html = '';
                var dayCount = 1;
                var nextMonthDay = 1;
                
                // 生成6周的日历
                for (var week = 0; week < 6; week++) {
                    html += '<tr>';
                    
                    for (var day = 0; day < 7; day++) {
                        var cellDate, cellMonth, cellYear, dateStr, dayNum, isCurrentMonth = false;
                        
                        if (week === 0 && day < firstDayWeek) {
                            // 上个月的日期
                            dayNum = prevMonthDays - firstDayWeek + day + 1;
                            cellYear = prevYear;
                            cellMonth = prevMonth;
                            dateStr = cellYear + '-' + String(cellMonth).padStart(2, '0') + '-' + String(dayNum).padStart(2, '0');
                        } else if (dayCount <= daysInMonth) {
                            // 当前月的日期
                            dayNum = dayCount++;
                            cellYear = year;
                            cellMonth = month;
                            dateStr = cellYear + '-' + String(cellMonth).padStart(2, '0') + '-' + String(dayNum).padStart(2, '0');
                            isCurrentMonth = true;
                        } else {
                            // 下个月的日期
                            dayNum = nextMonthDay++;
                            cellYear = month === 12 ? year + 1 : year;
                            cellMonth = month === 12 ? 1 : month + 1;
                            dateStr = cellYear + '-' + String(cellMonth).padStart(2, '0') + '-' + String(dayNum).padStart(2, '0');
                        }
                        
                        var today = new Date();
                        var isToday = (cellYear === today.getFullYear() && 
                                      cellMonth === today.getMonth() + 1 && 
                                      dayNum === today.getDate());
                        
                        var isWeekend = (day === 5 || day === 6); // 周六周日
                        var holiday = holidayData[dateStr];
                        var lunar = getLunarInfo(dateStr);
                        
                        var cellClass = 'calendar-day';
                        if (!isCurrentMonth) cellClass += ' other-month';
                        if (isToday) cellClass += ' today';
                        if (isWeekend) cellClass += ' weekend';
                        if (holiday) cellClass += ' holiday';
                        
                        html += '<td class="' + cellClass + '" data-date="' + dateStr + '">';
                        html += '<div class="calendar-date">' + String(dayNum).padStart(2, '0') + '</div>';
                        
                        if (lunar) {
                            html += '<div class="calendar-lunar">' + lunar + '</div>';
                        }
                        
                        if (holiday) {
                            console.log('找到节假日数据，日期:', dateStr, '节假日:', holiday);
                            var holidayClass = 'calendar-holiday';
                            if (holiday.type === '班') holidayClass += ' calendar-workday';
                            if (holiday.type === '假') holidayClass += ' calendar-special';
                            html += '<div class="' + holidayClass + '">' + holiday.name + '</div>';
                        } else {
                            // 只为当月日期输出调试信息
                            if (isCurrentMonth) {
                                console.log('当月日期无节假日数据:', dateStr);
                            }
                        }
                        
                        html += '</td>';
                    }
                    
                    html += '</tr>';
                    
                    // 如果已经显示完所有当月日期，且下个月已经显示了一周，就停止
                    if (dayCount > daysInMonth && nextMonthDay > 7) {
                        break;
                    }
                }
                
                console.log('生成HTML长度:', html.length);
                calendarBody.html(html);  
                console.log('日历生成完成，共', calendarBody.find('td').length, '个格子');
                
                // 绑定日期点击事件
                $('.calendar-day').click(function() {
                    var date = $(this).data('date');
                    var holiday = holidayData[date];
                    
                    if (holiday) {
                        // 如果已经有节假日设置，则编辑
                        openHolidayForm('edit', date, holiday);
                    } else {
                        // 如果没有节假日设置，则新增
                        openHolidayForm('add', date);
                    }
                });
                
                // 绑定节假日标签点击事件
                $('.calendar-holiday').click(function(e) {
                    e.stopPropagation(); // 阻止冒泡到日期点击事件
                    var date = $(this).closest('.calendar-day').data('date');
                    var holiday = holidayData[date];
                    openHolidayForm('edit', date, holiday);
                });
            }
            
            // 初始化日历 - 先显示空日历，再加载数据
            generateCalendar(currentYear, currentMonth);
            
            // 然后加载节假日数据并刷新
            loadHolidayData(function() {
                generateCalendar(currentYear, currentMonth);
            });
            
            // 上个月按钮
            $('#prevMonth').click(function() {
                currentMonth--;
                if (currentMonth < 1) {
                    currentMonth = 12;
                    currentYear--;
                }
                loadHolidayData(function() {
                    generateCalendar(currentYear, currentMonth);
                });
            });
            
            // 下个月按钮
            $('#nextMonth2').click(function() {
                currentMonth++;
                if (currentMonth > 12) {
                    currentMonth = 1;
                    currentYear++;
                }
                loadHolidayData(function() {
                    generateCalendar(currentYear, currentMonth);
                });
            });
            
            // 今天按钮
            $('#nextMonth').click(function() {
                var today = new Date();
                currentYear = today.getFullYear();
                currentMonth = today.getMonth() + 1;
                loadHolidayData(function() {
                    generateCalendar(currentYear, currentMonth);
                });
            });
            
            // 打开节假日设置表单
            function openHolidayForm(action, date, holiday) {
                var title = action === 'edit' ? '修改节假日设置' : '新增节假日设置';
                var url = '/HolidaysSet/Form?action=' + action + '&date=' + date;
                
                if (action === 'edit' && holiday) {
                    url += '&id=' + holiday.id + '&holidayType=' + holiday.type + '&holidayName=' + holiday.name;
                    console.log('编辑模式，传递ID:', holiday.id);
                }
                
                layer.open({
                    type: 2,
                    title: title,
                    area: ['400px', '300px'],
                    maxmin: false,
                    content: url,
                    success: function(layero, index) {
                        // 表单打开成功回调
                    },
                    end: function() {
                        // 表单关闭后刷新日历数据
                        loadHolidayData(function() {
                            generateCalendar(currentYear, currentMonth);
                        });
                    }
                });
            }
            
            // 加载节假日数据
            function loadHolidayData(callback) {
                console.log('=== 开始加载节假日数据 ===');
                console.log('请求参数:', { year: currentYear, month: currentMonth });
                
                $.get('/HolidaysSet/GetByYearMonth', {
                    year: currentYear,
                    month: currentMonth
                })
                .done(function(result) {
                    console.log('=== 服务器响应 ===');
                    console.log('完整响应:', result);
                    console.log('响应类型:', typeof result);
                    console.log('响应JSON字符串:', JSON.stringify(result, null, 2));
                    
                    if (result.Success || result.success) {
                        // 清空现有数据
                        holidayData = {};
                        console.log('清空holidayData，准备重新加载');
                        
                        var dataList = result.Data || result.data || [];
                        console.log('数据列表:', dataList);
                        console.log('数据条数:', dataList.length);
                        
                        // 处理每条数据
                        dataList.forEach(function(item, index) {
                            try {
                                console.log(`=== 处理第${index + 1}条数据 ===`);
                                console.log('原始数据项:', JSON.stringify(item, null, 2));
                                
                                var dateStr = '';
                                
                                // 检查所有可能的日期字段（注意大小写）
                                console.log('HolidaysTimeString:', item.HolidaysTimeString, typeof item.HolidaysTimeString);
                                console.log('holidaysTimeString:', item.holidaysTimeString, typeof item.holidaysTimeString);
                                console.log('HolidaysTimeIso:', item.HolidaysTimeIso, typeof item.HolidaysTimeIso);
                                console.log('holidaysTimeIso:', item.holidaysTimeIso, typeof item.holidaysTimeIso);
                                console.log('HolidaysTime:', item.HolidaysTime, typeof item.HolidaysTime);
                                console.log('holidaysTime:', item.holidaysTime, typeof item.holidaysTime);
                                
                                // 优先级处理（兼容大小写）
                                if (item.HolidaysTimeString || item.holidaysTimeString) {
                                    dateStr = String(item.HolidaysTimeString || item.holidaysTimeString).trim();
                                    console.log('使用TimeString字段，处理后:', dateStr);
                                } else if (item.HolidaysTimeIso || item.holidaysTimeIso) {
                                    dateStr = String(item.HolidaysTimeIso || item.holidaysTimeIso).trim();
                                    console.log('使用TimeIso字段，处理后:', dateStr);
                                } else if (item.HolidaysTime || item.holidaysTime) {
                                    // 尝试多种方式处理日期
                                    var timeField = item.HolidaysTime || item.holidaysTime;
                                    if (typeof timeField === 'string') {
                                        if (timeField.indexOf('T') > 0) {
                                            // ISO格式：2025-06-27T12:00:00+08:00
                                            dateStr = timeField.split('T')[0];
                                        } else {
                                            dateStr = timeField;
                                        }
                                    } else {
                                        // 作为Date对象处理
                                        var dateObj = new Date(timeField);
                                        dateStr = dateObj.toISOString().substr(0, 10);
                                    }
                                    console.log('从Time字段解析得到:', dateStr);
                                }
                                
                                // 验证和添加数据
                                if (dateStr && dateStr.length >= 10) {
                                    // 确保格式正确
                                    dateStr = dateStr.substr(0, 10);
                                    console.log('最终日期字符串:', dateStr);
                                    
                                    // 创建节假日对象（兼容大小写）
                                    var holidayType = item.HolidaysType || item.holidaysType;
                                    var holidayId = item.Id || item.id;
                                    var holidayObj = {
                                        name: getHolidayDisplayName(holidayType),
                                        type: holidayType,
                                        id: holidayId
                                    };
                                    
                                    // 添加到holidayData
                                    holidayData[dateStr] = holidayObj;
                                    console.log('成功添加节假日数据:', dateStr, '→', holidayObj);
                                } else {
                                    console.error('无法解析日期，数据项:', item);
                                }
                            } catch (e) {
                                console.error('处理第' + (index + 1) + '条数据出错:', e, item);
                            }
                        });
                        
                        console.log('=== 数据处理完成 ===');
                        console.log('最终holidayData对象:', holidayData);
                        console.log('holidayData键值:', Object.keys(holidayData));
                        console.log('加载节假日数据成功:', dataList.length, '条记录');
                    } else {
                        console.warn('服务器返回失败:', result.Message || result.message);
                    }
                    
                    // 执行回调函数
                    if (callback && typeof callback === 'function') {
                        console.log('执行回调函数');
                        callback();
                    }
                })
                .fail(function(xhr, status, error) {
                    console.error('网络请求失败:', { xhr, status, error });
                    console.error('响应文本:', xhr.responseText);
                    
                    // 即使失败也执行回调
                    if (callback && typeof callback === 'function') {
                        callback();
                    }
                });
            }
            
            // 刷新日历数据（供子窗口调用）
            window.refreshCalendar = function() {
                console.log('开始刷新日历数据...');
                loadHolidayData(function() {
                    generateCalendar(currentYear, currentMonth);
                    console.log('日历数据刷新完成');
                });
            };
            
            // 获取节假日类型显示名称
            function getHolidayDisplayName(type) {
                switch(type) {
                    case '假': return '假';
                    case '班': return '班';
                    case 'holiday': return '法定节假日';
                    case 'workday': return '调休工作日';
                    case 'weekend': return '周末';
                    default: return type;
                }
            }
                
            } // end of initializeCalendar function
        });
    </script>
</body>
</html>  